package com.guiwu.gteway.industryapp.Device.View;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.guiwu.gteway.industryapp.Api.GuiwuApi;
import com.guiwu.gteway.industryapp.Api.GuiwuApiCallback;
import com.guiwu.gteway.industryapp.Data.DataRepository;
import com.guiwu.gteway.industryapp.Device.module.CameraInfo;
import com.guiwu.gteway.industryapp.Device.module.EventBean;
import com.guiwu.gteway.industryapp.Device.module.GateWay;
import com.guiwu.gteway.industryapp.Device.module.Monitor;
import com.guiwu.gteway.industryapp.Device.module.MonitorData;
import com.guiwu.gteway.industryapp.Device.module.MonitorGroup;

import com.guiwu.gteway.industryapp.GateWayInfo.GateWayInfoPresenter;
import com.guiwu.gteway.industryapp.R;
import com.guiwu.gteway.industryapp.RootActivity;
import com.guiwu.gteway.industryapp.util.SoftKeyboardStateHelper;
import com.guiwu.gteway.industryapp.widget.MViewPager;

import com.guiwu.gteway.industryapp.widget.SimpleToolbar;
import com.guiwu.gteway.industryapp.util.MyLog;
import com.guiwu.gteway.industryapp.util.PreferencesUtil;
import com.guiwu.gteway.industryapp.util.ProgressSimpleDialog;
import com.videogo.errorlayer.ErrorInfo;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.EZPlayer;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by qiaoguan on 2018/3/7. 监控点的activity页面  监控点列表 -->摄像头列表-->监控点数值(周期)-->网关绑定事件(周期)
 */

public class MonitorActivity extends RootActivity implements Handler.Callback ,MViewPager.OnPageChangeListener ,View.OnClickListener{
    private static final String TAG = "MonitorActivity";

    public static final String GATEWAY = "com.guiwu.gateway.industryapp.Device.MonitorActivity.GATEWAY";
    public static final String GATEWAY_SN = "com.guiwu.gateway.industryapp.Device.MonitorActivity.SN";
    public static final String DIALOG_VIDEO = "DialogViedo";
    public static final int REQUEST_DATA_TIMEER = 0x06;

    private Handler mMessageHandler;

    private MViewPager mViewPager;
    private TabLayout mTabLayout;
    private LinearLayout parent;
    private SimpleToolbar simpleToolBar;
    private ScrollView scrollView;
    private SurfaceView videoView;
    private LinearLayout videoRefreshLinear;
    private TextView refreshMsg ,refreshBt;
    private LinearLayout monitorRefreshLayout;
    private TextView monitorRefreshBt;
    private ExecutorService service;
    VideoPickerFragment videoPick;


    private GateWay mGateWay;
    private String mUserId;
    private List<MonitorGroup> monitorGroups = new ArrayList<>();
    private List<Fragment> mFragments = new ArrayList<>(4);
    private List<String> mTitles = new ArrayList<>(4);
    private List<CameraInfo> cameraInfos = new ArrayList<>();
    private ProgressSimpleDialog progressDialog;

    private List<EventBean> eventList = new ArrayList<>();
    private String eventInfo;

    private ViewPagerAdapter mFragmentAdapter;
    private SurfaceHolder svHolder;

    private EZOpenSDK ezOpenSDK;
    private EZPlayer ezPlayer;
    private Runnable queryRunnable;

    private boolean videoInWindow;
    private long flag;
    private int currentPagerIndex;
    private int currentVideoIndex;

    public boolean stopUpdate = false;


    private GateWayInfoPresenter mInfoPresenter;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.monitory_layout);
        initDate();
        initView();
        initFragments();
        initViewPager();
        queryMonitorGroups();
    }

    //给子页面数据获取的方法
    public GateWay getmGateWay(){
        return this.mGateWay;
    }
    public List<MonitorGroup> getMonitorGroups(){
        MyLog.i("monitorGroups","初始化：" + monitorGroups.hashCode());
        return monitorGroups;
    }
    public String getEventInfo(){return this.eventInfo;}
    public EZPlayer getEzPlayer(){
        return this.ezPlayer;
    }
    public List<CameraInfo> getCameraInfos(){
        return cameraInfos;
    }

    public CameraInfo getCurrentCameraInfo(){
        return cameraInfos.get(currentVideoIndex);
    }

    public EZOpenSDK getEzOpenSDK(){
        return ezOpenSDK;
    }

    private void initDate(){
        ezOpenSDK = EZOpenSDK.getInstance();
        mGateWay = getIntent().getParcelableExtra(GATEWAY);
        DataRepository.getInstance().setmCurrentGateWay(mGateWay);
        mUserId = String.valueOf(PreferencesUtil.getInstance(getApplicationContext()).getInt("userId",0));
        mMessageHandler = new Handler(this);
        service = Executors.newCachedThreadPool();
    }

    private void initView(){
        videoView = findViewById(R.id.monitory_surfaceView);
        progressDialog = new ProgressSimpleDialog(this);
        parent = findViewById(R.id.parent_layout);
        scrollView = findViewById(R.id.monitor_scrollview);
        //重新绘制viewPager
        parent.post(new Runnable() {
            @Override
            public void run() {
             //   scrollToMiss();
                scrollToShow();
            }
        });

        //标题栏
        simpleToolBar = findViewById(R.id.monitor_simple_toolbar);
        simpleToolBar.setRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentPagerIndex == 3){
                    //Toast.makeText(getApplicationContext(),"切换摄像头",Toast.LENGTH_SHORT).show();
                    changeVideo();
                }else {
                    if (videoInWindow){
                        scrollToMiss();
                    }else
                        scrollToShow();
                }
            }
        });

        simpleToolBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        //监听键盘上下
        final SoftKeyboardStateHelper softKeyboardStateHelper = new SoftKeyboardStateHelper(parent);
        softKeyboardStateHelper.addSoftKeyboardStateListener(new SoftKeyboardStateHelper.SoftKeyboardStateListener() {
            @Override
            public void onSoftKeyboardOpened(int keyboardHeightInPx) {

            }

            @Override
            public void onSoftKeyboardClosed() {
                stopUpdate = false;
                ((MonitorAlarmFragment)mFragmentAdapter.getItem(1)).searchEditText.clearFocus();
            }
        });

        //摄像头刷新
        refreshBt = findViewById(R.id.video_refresh);
        refreshBt.setOnClickListener(this);
        refreshMsg = findViewById(R.id.video_refresh_msg);
        videoRefreshLinear = findViewById(R.id.video_refresh_linear_layout);

        //网关刷新
        monitorRefreshLayout = findViewById(R.id.refresh_monitor_layout);
        monitorRefreshBt = findViewById(R.id.refresh_monitor);
        //monitorRefreshBt.setOnClickListener(this);
        monitorRefreshLayout.setOnClickListener(this);
    }


    //视频初始化
    private void pressCameraInfo(String jsonString) throws JSONException{
        JsonObject jsonObject = new JsonParser().parse(jsonString).getAsJsonObject();
        int erron = jsonObject.get("errno").getAsInt();
        if (erron == 0){
            JsonArray jsonArray = jsonObject.getAsJsonArray("data");
            Gson gson = new Gson();
            cameraInfos = gson.fromJson(jsonArray, new TypeToken<List<CameraInfo>>() {}.getType());
        }else {
            MyLog.e(TAG,jsonObject.get("error").getAsString());
        }
    }
    //获取摄像头的accessToken  times 是请求的次数，每个摄像头都要请求一遍获取acssToken
    private void getAccessTokenFromGuiwu(final CameraInfo cameraInfo) throws JSONException{
        GuiwuApi.getVideoAcessToken(cameraInfo.getDeviceSerial(), new GuiwuApiCallback() {
            @Override
            public void onSuccess(String response) {
                JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                int erron = jsonObject.get("errno").getAsInt();
                if (erron == 0){
                    JsonArray jsonArray = jsonObject.getAsJsonArray("data");
                    JsonObject accessTokenObject = jsonArray.get(0).getAsJsonObject();
                    String accessToken = accessTokenObject.get("accessToken").getAsString();
                    cameraInfo.setAcessToken(accessToken);
                    MyLog.i(TAG,"摄像头" + cameraInfo.getDeviceName() +"  token获取成功" + cameraInfo.getAcessToken());
                    boolean isSend = true;
                    for (CameraInfo info : cameraInfos){
                        if (info.getAcessToken() == null)
                            isSend = false;
                    }
                    if (isSend)
                        showVideo(0);
                }else{
                    MyLog.i(TAG,"摄像头" + cameraInfo.getDeviceName() +"  token获取失败" + jsonObject.get("error").getAsString());
                   progressDialog.closeProgressDialog();
                }
            }

            @Override
            public void onFailed(Exception e) {
                MyLog.i(TAG,"摄像头" + cameraInfo.getDeviceName() +"  token获取失败" + e.getMessage());
               progressDialog.closeProgressDialog();
            }
        });
    }

    //默认视频
    private void showVideo(int currentVideoIndex){
        MyLog.i(TAG,"进入showVideo");
        this.currentVideoIndex = currentVideoIndex;
        svHolder = videoView.getHolder();
        MyLog.i(TAG,cameraInfos.size() + "  ----currentIndex  " + currentVideoIndex);
        if (cameraInfos.size() > 0 && cameraInfos.size() >= currentVideoIndex){
            CameraInfo info = cameraInfos.get(currentVideoIndex);
            String TokenFromCamera = info.getAcessToken();
            if (TokenFromCamera ==null)
                return;

            MyLog.i(TAG,"开始setAccess");
            ezOpenSDK.setAccessToken(TokenFromCamera);

            //清空上一个记录
            if (ezPlayer != null){
                ezPlayer.release();
                ezPlayer = null;
            }

            MyLog.i(TAG,"开始创建ezPlayer");
            ezPlayer = ezOpenSDK.createPlayer(info.getDeviceSerial(),info.getChannelNo());

            if (ezPlayer == null)
                return;

            if (!info.getValidCode().equals("")){
                ezPlayer.setPlayVerifyCode(info.getValidCode());
            }

            ezPlayer.setHandler(mMessageHandler);
            ezPlayer.setSurfaceHold(svHolder);
            MyLog.i(TAG,"发送请求摄像头");
            ezPlayer.startRealPlay();
        }
    }

    private void changeVideo(){
        //打开切换摄像头对话框
        FragmentManager manager = getSupportFragmentManager();
        videoPick = new VideoPickerFragment();
        videoPick.show(manager,DIALOG_VIDEO);
        videoPick.setOnSelectListener(new VideoPickerFragment.OnSelectIndexListener() {
            @Override
            public void onSelectIndex(int index) {
              //  Toast.makeText(getApplicationContext(),"点击了第" + index + "条",Toast.LENGTH_SHORT).show();
                videoPick.dismiss();
                if (index == currentVideoIndex)
                    return;
                progressDialog.showPorgressDialog(getString(R.string.video_pick_progress));
                showVideo(index);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        queryMonitorGroups();
        MyLog.i(TAG,"onResume");
    }
    @Override
    protected void onPause() {
        MyLog.i(TAG,"onPause");
        cancleQuery();
        super.onPause();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ezPlayer != null){
            ezPlayer.release();
        }
        cancleQuery();
        DataRepository.getInstance().clearCurrentGateWay();
    }

    //viewPager初始化
    private void initFragments(){
        mFragments.add(MonitorListFragment.newInstance(mGateWay.getSn()));
        mFragments.add(MonitorAlarmFragment.newInstance(mGateWay.getSn()));
        MonitorInfoFragment infoFragment = MonitorInfoFragment.newInstance(mGateWay);
        mInfoPresenter = new GateWayInfoPresenter(infoFragment);
        mFragments.add(infoFragment);
        mFragments.add(MonitorVideoFragment.newInstance());
        mTitles.add(getString(R.string.monitor_table_title_list));
        mTitles.add(getString(R.string.monitor_table_title_alarm));
        mTitles.add(getString(R.string.monitor_table_title_base_info));
        mTitles.add(getString(R.string.monitor_table_title_video));


    }
    private void initViewPager(){
        mTabLayout = findViewById(R.id.monitory_tab_layout);
        mViewPager = findViewById(R.id.monitory_viewPager);
        mViewPager.setOffscreenPageLimit(mFragments.size());
        mFragmentAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        mViewPager.setAdapter(mFragmentAdapter);
        mViewPager.setCanScroll(false);
        mTabLayout.setupWithViewPager(mViewPager,true);
        mViewPager.addOnPageChangeListener(this);


    }

    //设置viewPager的重新绘制的高度  变长
    private void expendLayout(){
        int mianHeight = parent.getHeight();
        int barHeight = simpleToolBar.getHeight();
        int tabHeight = mTabLayout.getHeight();
        int pxHeight  =  mianHeight-barHeight - tabHeight;
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mViewPager.getLayoutParams();
        lp.height =  pxHeight;
        mViewPager.setLayoutParams(lp);
     //   viewPager.requestLayout();
    }
    //压缩
    private void compressLayout(){
        int mianHeight = parent.getHeight();
        int barHeight = simpleToolBar.getHeight();
        int tabHeight = mTabLayout.getHeight();
        int vedioHeight = videoView.getHeight();

        int pxHeight = mianHeight - barHeight - tabHeight - vedioHeight;
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mViewPager.getLayoutParams();
        lp.height = pxHeight;
        mViewPager.setLayoutParams(lp);
    }

    //获取监控点列表
    private void queryMonitorGroups(){
       progressDialog.showPorgressDialog("正在获取信息");
        //
        String gateWaySn = mGateWay.getSn();
        GuiwuApi.getMonitorPoints(gateWaySn,mUserId,new GuiwuApiCallback() {
            @Override
            public void onSuccess(String response) {
                MyLog.i(TAG,"获取监控点列表请求成功：" + response);
            //    progressDialog.closeProgressDialog();
                getCameraInfoFromGuiwu();
                pressDataIntoMonitorGrop(response);
           //     ((MonitorListFragment)mFragmentAdapter.getItem(0)).updateUI();
            }

            @Override
            public void onFailed(Exception e) {
                MyLog.i(TAG,"获取监控点列表出错：" + e.getMessage());
                Toast.makeText(getApplicationContext(),getString(R.string.toast_error_monitor),Toast.LENGTH_SHORT).show();
               progressDialog.closeProgressDialog();
               handlerGetDateFailed();
            }
        });
    }

    //获取网关下的摄像头列表  "在获取监控点之后"
    private void getCameraInfoFromGuiwu(){
        GuiwuApi.getGateWayVideoInfo(mGateWay.getSn(), new GuiwuApiCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    MyLog.i(TAG,"获取摄像头列表成功：" + response);
                    pressCameraInfo(response);
                    MyLog.i(TAG,"jason转换成功：" + cameraInfos);
                    if (cameraInfos.size() == 0) { //没有绑定摄像头
                        Toast.makeText(getApplicationContext(),getString(R.string.toast_video_notice),Toast.LENGTH_SHORT).show();
                        //isDialogShow = progressDialog.closeProgressDialog();
                        handlerNoCamera();
                        queryMonitorData();
                    }
                    else {
                        for (int i = 0; i< cameraInfos.size() ;i++){
                            getAccessTokenFromGuiwu(cameraInfos.get(i));
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    MyLog.i(TAG,"获取摄像头列表失败：" + e.getMessage());
                 progressDialog.closeProgressDialog();
                }
            }

            @Override
            public void onFailed(Exception e) {
                MyLog.i(TAG,"获取摄像头列表失败：" + e.getMessage());
              progressDialog.closeProgressDialog();
            }
        });
    }

    //周期任务
    private Timer timer;
    private void setQueryTask(){
        if (timer == null && currentPagerIndex == 0) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Message message = new Message();
                    message.what = REQUEST_DATA_TIMEER;
                    mMessageHandler.sendMessage(message);
                }
            },3000,3000);
        }
    }
    //周期更新监控点数据
    private void queryMonitorData(){
                    String gateWayId = mGateWay.getGateWayId();
                    String apiKey = mGateWay.getApiKey();
                    GuiwuApi.getMonitorData(gateWayId, apiKey, new GuiwuApiCallback() {
                        @Override
                        public void onSuccess(String response) {
                            MyLog.i(TAG, "周期获取监控点数据请求成功：" + response);
                            handleMonitorData(response);
                            queryMonitorEvent();
                        }

                        @Override
                        public void onFailed(Exception e) {
                            MyLog.e(TAG, "周期获取监控点列表请求失败：" + e.getMessage());
                            handlerGetDateFailed();
                        }
                    });
    }

    //周期更新监控点数据 包括第一次
    private void queryMonitorData1(){
        if (queryRunnable == null){
            queryRunnable = new Runnable() {
                @Override
                public void run() {
                    String gateWayId = mGateWay.getGateWayId();
                    String apiKey = mGateWay.getApiKey();
                    GuiwuApi.getMonitorData(gateWayId,apiKey,new GuiwuApiCallback() {
                        @Override
                        public void onSuccess(String response) {
                            MyLog.i(TAG,"周期获取监控点数据请求成功：" + response);
                            handleMonitorData(response);
                            //  if (handleResend()){

//                            if (!stopUpdate)
//                                ((MonitorListFragment)mFragmentAdapter.getItem(0)).updateUI();
                            //    }
                            queryMonitorEvent();
                        }

                        @Override
                        public void onFailed(Exception e) {
                            MyLog.e(TAG,"周期获取监控点列表请求失败：" + e.getMessage());
                            handlerGetDateFailed();
                        }
                    });

                }
            };
        }

      //  mMessageHandler.post(queryRunnable);
    }
    private void cancleQuery(){
        if (timer != null){
            timer.cancel();
            timer = null;
        }
    }

    //查询网关事件列表
    private void queryMonitorEvent(){
        GuiwuApi.queryQueryEventList(mGateWay.getSn(), new GuiwuApiCallback() {
            @Override
            public void onSuccess(String response) {
                MyLog.i(TAG, "查询事件列表成功：" + response);
                pressDataIntoEventList(response);
                findRegistEvent();
            }

            @Override
            public void onFailed(Exception e) {
                MyLog.e(TAG,"查询事件列表失败：" + e.getMessage());
                handlerGetDateFailed();
            }
        });
    }
    private void findRegistEvent(){
        GuiwuApi.findRegistEvent(mGateWay.getSn(), new GuiwuApiCallback() {
            @Override
            public void onSuccess(String response) {
              //  MyLog.i(TAG, "查询寄存器事件成功：" + response);
                JsonObject jb = getJsonObj(response,"查寄存器事件");
                if (jb != null){
                    findEventInfo(jb);
                    progressDialog.closeProgressDialog();
                }

                if (!stopUpdate){
                    //循环
                   // if (mMessageHandler.hasMessages())
                    setQueryTask();
                    monitorRefreshLayout.setVisibility(View.GONE);
                    ((MonitorListFragment)mFragmentAdapter.getItem(0)).updateUI();
                }

            }

            @Override
            public void onFailed(Exception e) {
                MyLog.e(TAG,"查询寄存器事件失败：" + e.getMessage());
                handlerGetDateFailed();
            }
        });
    }

    //将json值填充到monitor groups中去
    private void pressDataIntoMonitorGrop(String response){
        try{
            JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
            int erron = jsonObject.get("errno").getAsInt();
            if (erron == 0){
                JsonArray jsonArray = jsonObject.getAsJsonArray("data");
                Gson gson = new Gson();
                monitorGroups = gson.fromJson(jsonArray, new TypeToken<List<MonitorGroup>>() {}.getType());
                transLate();
                MyLog.i(TAG,"监控点列表类型解析成功" +monitorGroups);
            }else {
                MyLog.i(TAG,"监控点列表类型解析出现问题：" + jsonObject.get("error").getAsString());
            }

        }catch (JsonParseException e){
            MyLog.i(TAG,"监控点列表解析出现问题：" + e.getMessage());
        }
    }

    //将监控点组分类
    private void transLate(){
        MyLog.i("monitorGroups","填入类型前：" + monitorGroups.hashCode());
        for (MonitorGroup group : monitorGroups){
            List<Monitor> monitors = new ArrayList<>();
            for (MonitorData perMonitorData : group.getMonitorData()){
                if (perMonitorData != null){
                    Monitor monitor = null;
                    switch (perMonitorData.getBindDeviceType()){
                        case "local":
                            monitor = perMonitorData.getAsLocal();
                            break;
                        case "DELTA":
                            monitor = perMonitorData.getAsPLC();
                            break;
                        case "MODBUS":
                            monitor = perMonitorData.getAsModbus();
                            break;
                    }
                    monitors.add(monitor);
                }
            }
            group.setMonitors(monitors);
        }
        MyLog.i("monitorGroups","填入类型后：" + monitorGroups.hashCode());

    }

    //将从oneNet获取到的值填充到监控点组中去  赋予监控点value
    private void handleMonitorData(String response){
        MyLog.i("monitorGroups","填入数据前：" + monitorGroups.hashCode());
        try{
            JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
            int erron = jsonObject.get("errno").getAsInt();
            if (erron == 0){
                JsonObject jsonObject1 = jsonObject.get("data").getAsJsonObject();
                JsonArray jsonArray = jsonObject1.getAsJsonArray("datastreams");

                List<Monitor> allMonitors = new ArrayList<>();
                for (MonitorGroup group : monitorGroups){
                    allMonitors.addAll(group.getMonitors());
                }

                //填充数值
                for (Monitor perMonitor : allMonitors){
                    for (JsonElement element : jsonArray){
                        JsonObject perObject =  element.getAsJsonObject();
                        String jsonId = perObject.get("id").getAsString();
                        if (jsonId.equalsIgnoreCase(perMonitor.getStreamID())){
                             JsonArray perArray = perObject.get("datapoints").getAsJsonArray();
                             JsonObject object = perArray.get(0).getAsJsonObject();
                             String jsonTime = object.get("at").getAsString();
                             int jsonValue = object.get("value").getAsInt();
                             perMonitor.setValue(jsonValue);
                             perMonitor.setDataString(jsonTime);
                        }else if (jsonId.equalsIgnoreCase(perMonitor.getMirrorId())){//镜像id
                            JsonArray perArray = perObject.get("datapoints").getAsJsonArray();
                            JsonObject object = perArray.get(0).getAsJsonObject();
                            String jsonTime = object.get("at").getAsString();
                            int jsonValue = object.get("value").getAsInt();
                            if (jsonValue == 0)//异常
                                perMonitor.setAbnormal(true);
                            else
                                perMonitor.setAbnormal(false);
                        }

                    }
                }
                MyLog.i(TAG,"填充oneNet返回数据成功" + monitorGroups);
            //    MyLog.i("monitorGroups","填充oneNet返回数据成功：" + monitorGroups.hashCode());
            }else
                MyLog.e(TAG,"填充oneNet返回数据失败：" + jsonObject.get("error").getAsString());
        }catch (JsonParseException e){
            MyLog.e(TAG,"填充oneNet返回数据失败：" + e.getMessage());
        }
        MyLog.i("monitorGroups","填入数据后：" + monitorGroups.hashCode());
    }

    //json填充到事件列表中
    private void pressDataIntoEventList(String response){
      //  eventList =
    //    List<EventBean> list = analyseJson(response,"事件列表",eventList);
      //  eventList = list;
        try{
            JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
            int erron = jsonObject.get("errno").getAsInt();
            if (erron == 0){
                JsonArray jsonArray = jsonObject.getAsJsonArray("data");
                Gson gson = new Gson();
                eventList = gson.fromJson(jsonArray, new TypeToken<List<EventBean>>() {}.getType());
                MyLog.i(TAG,"事件列表解析成功");
            }else {
                MyLog.i(TAG,"事件列表解析出现问题：" + jsonObject.get("error").getAsString());
            }

        }catch (JsonParseException e){
            MyLog.i(TAG,"事件列表列表解析出现问题：" + e.getMessage());
        }

    }

    //找到事件
    private void findEventInfo(JsonObject jsonObject){
        int isBind = jsonObject.get("isBind").getAsInt();
        if (isBind == 1){//没有绑定寄存器事件
            eventInfo = getString(R.string.monitor_label_no_event);
        }else {
            int modbusAd = jsonObject.get("modbusRegisterAdd").getAsInt();
            String nickName = jsonObject.get("bindDeviceNickName").getAsString();
            String dataType = jsonObject.get("dataType").getAsString();
            String addressType = jsonObject.get("addressType").getAsString();
            int address = jsonObject.get("address").getAsInt();
            //找到寄存器
            if (monitorGroups.size() > 0){
                List<Monitor> allMonitors = new ArrayList<>();
                for (MonitorGroup group : monitorGroups){
                    allMonitors.addAll(group.getMonitors());
                }
                for (Monitor perMonitor : allMonitors){
                    if (    perMonitor.getDataType().equalsIgnoreCase(dataType)
                            && perMonitor.getModBusAdd() == modbusAd
                            && perMonitor.getNickName().equalsIgnoreCase(nickName)
                            && perMonitor.getAddressType().equalsIgnoreCase(addressType)
                            && perMonitor.getAddressAdd() == address){ //是他了
                            for (EventBean eventBean : eventList){
                                if (eventBean.getEventId() == perMonitor.getValueInt()){
                                    eventInfo = eventBean.getContent();
                                }
                            }

                            return;
                    }


                }
            }
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        currentPagerIndex = position;
        if (position != 0){
            MyLog.i(TAG,"ViewPager位置" + position);
            cancleQuery();
        }else {
            queryMonitorData();
        }

        if (position != 3){//其他页面
            simpleToolBar.setRightIcon(R.mipmap.video48);
//            if (videoInWindow)
//                scrollToMiss();
        }else {//视频页面
            simpleToolBar.setRightIcon(R.mipmap.list48);
//            if (!videoInWindow)
               scrollToShow();
        }

    }
    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public void onBackPressed() {
            super.onBackPressed();
    }

    private class ViewPagerAdapter extends FragmentPagerAdapter{

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles.get(position);
        }
    }

    //handler接收消息的回调
    @Override
    public boolean handleMessage(Message msg) {
        if (this.isFinishing()) {
            return false;
        }
        switch (msg.what){
            case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS:
                MyLog.i(TAG,"播放成功");
                videoRefreshLinear.setVisibility(View.GONE);
                //开启周期查询
                if (currentPagerIndex == 0)
                    queryMonitorData();
                else {
                    progressDialog.closeProgressDialog();
                }

                break;
            case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_FAIL:
                handlePlayFailed(msg.obj);
              progressDialog.closeProgressDialog();
                break;

            case REQUEST_DATA_TIMEER:
                queryMonitorData();
                break;
        }
        return false;
    }

    //处理播放失败
    private void handlePlayFailed(Object erObject){
        if (erObject != null) {
            ErrorInfo errorInfo = (ErrorInfo) erObject;
            MyLog.i(TAG,"播放失败,失败码" + errorInfo.errorCode  + "  原因：" + errorInfo.description);
            videoRefreshLinear.setVisibility(View.VISIBLE);
            StringBuilder sb = new StringBuilder(refreshMsg.getText());
            sb.append(errorInfo.description).append("。");
            refreshMsg.setText(sb);
        }
        if(ezPlayer != null){
            ezPlayer.stopRealPlay();
        }
    }

    //处理没有绑定摄像头
    private void handlerNoCamera(){
        simpleToolBar.setTvRightEnable(false);
        scrollToMiss();
        LinearLayout tabStrip = (LinearLayout)mTabLayout.getChildAt(0);
        View tabView = tabStrip.getChildAt(3);
        tabView.setClickable(false);
//        for (int i = 0; i < tabStrip.getChildCount(); i++) {
//            View tabView = tabStrip.getChildAt(i);
//            if (tabView != null) {
//                tabView.setClickable(false);
//            }
//        }

    }

    //处理周期获取数据失败
    private void handlerGetDateFailed(){
        progressDialog.closeProgressDialog();
        monitorRefreshLayout.setVisibility(View.VISIBLE);
        cancleQuery();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.video_refresh :
                progressDialog.showPorgressDialog("刷新中");
                videoRefreshLinear.setVisibility(View.GONE);
                refreshMsg.setText(getString(R.string.video_error));
                if(ezPlayer != null){
                    ezPlayer.startRealPlay();
                }
                break;
            case R.id.refresh_monitor_layout:
                queryMonitorGroups();
                break;
        }
    }


    //启动方法
    public static void actionStart(Context packageContext, GateWay gateWay){
        Intent intent = new Intent(packageContext,MonitorActivity.class);
        intent.putExtra(GATEWAY,gateWay);
        packageContext.startActivity(intent);
    }

    //将滚轮移动到底部
    private void scrollToMiss(){
        expendLayout();
        if (scrollView != null) {
            mMessageHandler.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(View.FOCUS_DOWN);
                }
            });
            videoInWindow = false;
        }
    }
    //滚轮移动到顶部
    private void scrollToShow(){
        compressLayout();
        if (scrollView != null)
            mMessageHandler.post(new Runnable() {
                @Override
                public void run() {
                    scrollView.fullScroll(View.FOCUS_UP);
                }
            });
        videoInWindow = true;
    }


    //使子view可以滚动
    public static void stopParentScroll(View view){
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
    }

    //解析常用json数据 //泛型有问题，待解决
//    private <T> List<T> analyseJson(String response,String Msg,List<T> returnList){
//
//        try{
//            JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
//            int erron = jsonObject.get("errno").getAsInt();
//            if (erron == 0){
//                JsonArray jsonArray = jsonObject.getAsJsonArray("data");
//                Gson gson = new Gson();
//                returnList = gson.fromJson(jsonArray, new TypeToken<List<T>>() {}.getType());
//                MyLog.i(TAG,Msg + "解析成功");
//            }else {
//                MyLog.i(TAG, Msg + "解析出现问题：" + jsonObject.get("error").getAsString());
//            }
//        }catch (JsonParseException e){
//            MyLog.i(TAG, Msg + "解析出现问题：" + e.getMessage());
//        }
//
//        return returnList;
//    }

    public  JsonObject getJsonObj(String response,String Msg){

        JsonObject jsonObReturn = null;
        try{
            JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
            int erron = jsonObject.get("errno").getAsInt();
            if (erron == 0){
                JsonArray jsonArray = jsonObject.getAsJsonArray("data");
                if (jsonArray.size() == 1)
                    jsonObReturn = jsonArray.get(0).getAsJsonObject();
                MyLog.i(TAG,Msg + "解析成功");
            }else {
                MyLog.i(TAG, Msg + "解析出现问题：" + jsonObject.get("error").getAsString());
            }
        }catch (JsonParseException e){
            MyLog.i(TAG, Msg + "解析出现问题：" + e.getMessage());
        }

        return jsonObReturn;
    }

    public JsonArray getJsonAry(String response,String Msg ,String TAG){
        JsonArray jsonArray = null;
        try{
            JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
            int erron = jsonObject.get("errno").getAsInt();
            if (erron == 0){
                jsonArray = jsonObject.getAsJsonArray("data");
                MyLog.i(TAG,Msg + "解析成功");
            }else {
                MyLog.i(TAG, Msg + "解析出现问题：" + jsonObject.get("error").getAsString());
            }
        }catch (JsonParseException e){
            MyLog.i(TAG, Msg + "解析出现问题：" + e.getMessage());
        }

        return jsonArray;
    }


}
